<template>
  <div class="h-full flex flex-col bg-gray-50">
    <!-- Header -->
    <div class="bg-white border-b px-6 py-4 flex justify-between items-center">
      <h1 class="text-2xl font-bold text-gray-800">复盘计划</h1>
      <button class="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700" @click="openAdd">新增复盘</button>
    </div>

    <!-- Calendar Controls -->
    <div class="bg-white border-b px-6 py-2 flex items-center justify-between">
      <div class="flex items-center gap-4">
        <button class="p-1 hover:bg-gray-100 rounded" @click="prevWeek">&lt;</button>
        <span class="font-medium text-lg">{{ currentYear }}年{{ currentMonth }}月</span>
        <button class="p-1 hover:bg-gray-100 rounded" @click="nextWeek">&gt;</button>
      </div>
      <button class="text-blue-600 text-sm" @click="goToToday">回到今天</button>
    </div>

    <!-- Calendar Grid (Week View) -->
    <div class="bg-white border-b grid grid-cols-7">
      <div v-for="(day, idx) in weekDays" :key="idx" 
           class="border-r min-h-[120px] p-2 cursor-pointer hover:bg-blue-50 transition-colors relative"
           :class="{ 'bg-blue-50': isSelected(day.date), 'bg-yellow-50': isToday(day.date) }"
           @click="selectDate(day.date)">
        <div class="text-center mb-2">
          <div class="text-xs text-gray-500">{{ day.name }}</div>
          <div class="text-lg font-semibold" :class="{ 'text-blue-600': isToday(day.date) }">{{ day.day }}</div>
        </div>
        <!-- Task Dots/Count -->
        <div class="space-y-1">
          <div v-for="t in getTasksForDate(day.date).slice(0, 3)" :key="t.id" 
               class="text-xs border rounded px-1 py-0.5 truncate shadow-sm"
               :class="t.status === 'done' ? 'bg-gray-100 text-gray-400 line-through' : 'bg-white'">
             {{ getCardQuestion(t) }}
          </div>
          <div v-if="getTasksForDate(day.date).length > 3" class="text-xs text-gray-400 text-center">
            +{{ getTasksForDate(day.date).length - 3 }}
          </div>
        </div>
      </div>
    </div>

    <!-- Task List for Selected Date -->
    <div class="flex-1 overflow-auto p-6">
      <h2 class="text-lg font-semibold mb-4">{{ formatDate(selectedDate) }} 复盘内容 ({{ selectedTasks.length }})</h2>
      <div v-if="selectedTasks.length === 0" class="text-gray-400 text-center py-10">暂无复盘任务</div>
      <div class="space-y-4">
        <div v-for="t in sortedTasks" :key="t.id" 
             class="rounded shadow p-4 border-l-4 cursor-pointer transition-all hover:shadow-md"
             :class="t.status === 'done' ? 'bg-gray-50 border-gray-300' : 'bg-white border-blue-500'"
             @click="openReviewModal(t)">
          <div class="flex justify-between items-start">
            <div class="flex-1">
              <div class="font-medium text-lg mb-2" :class="{ 'line-through text-gray-500': t.status === 'done' }">
                {{ getCardQuestion(t) }}
              </div>
              <div class="mt-2 text-xs text-gray-400">
                来自知识点: {{ t.knowledge_title }} | 计划: {{ t.plan_type }}
              </div>
            </div>
            <div class="ml-4 flex flex-col gap-2">
              <span v-if="t.status === 'done'" class="text-green-600 text-sm font-bold">已完成</span>
              <button class="text-red-400 hover:text-red-600 text-sm" @click.stop="confirmDelete(t)">删除</button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Review Modal -->
    <div v-if="showReview" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50" @click.self="closeReviewModal">
      <div class="bg-white rounded-lg shadow-2xl w-full max-w-2xl flex flex-col p-6" style="max-height: 80vh;">
        <div class="flex justify-between items-start mb-4">
          <h2 class="text-xl font-bold text-gray-800">复盘卡片</h2>
          <button @click="closeReviewModal" class="text-gray-500 hover:text-gray-700 text-2xl">&times;</button>
        </div>
        
        <div class="flex-1 overflow-y-auto space-y-6 px-1" style="min-height: 0;">
          <div>
            <div class="text-sm text-gray-500 mb-1">问题</div>
            <div class="text-lg font-medium text-gray-900">{{ currentReviewTask?.question }}</div>
          </div>
          
          <div v-if="showAnswer">
            <div class="text-sm text-gray-500 mb-1 flex justify-between items-center">
              <span>答案</span>
              <button class="text-blue-600 text-xs hover:underline" @click="showAnswer = false">隐藏答案</button>
            </div>
            <div class="prose max-w-none bg-gray-50 p-4 rounded overflow-auto" style="max-height: 40vh;" v-html="currentReviewTask?.answer"></div>
          </div>
          
          <div v-else class="flex justify-center py-8">
            <button class="px-6 py-2 border border-blue-600 text-blue-600 rounded-full hover:bg-blue-50 transition-colors"
                    @click="showAnswer = true">
              显示答案
            </button>
          </div>
        </div>

        <div class="mt-6 pt-4 border-t flex justify-end gap-3 flex-shrink-0">
          <button class="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded" @click="jumpToKnowledgeAction(currentReviewTask)">
            查看原题
          </button>
          <button class="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded" @click="closeReviewModal">关闭</button>
          <button v-if="currentReviewTask?.status !== 'done'" 
                  class="px-6 py-2 bg-green-600 text-white rounded hover:bg-green-700 shadow-lg transform active:scale-95 transition-all"
                  @click="completeReview">
            完成复盘
          </button>
        </div>
      </div>
    </div>

    <!-- Delete Confirm Dialog -->
    <div v-if="showDelete" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50" @click.self="cancelDelete">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6">
        <h3 class="text-lg font-bold text-gray-800 mb-4">删除复盘任务</h3>
        <p class="text-gray-600 mb-6">您想要删除当前的复盘任务，还是删除整个复盘计划？</p>
        
        <div class="flex flex-col gap-3">
          <button class="w-full py-2 border border-red-200 text-red-600 rounded hover:bg-red-50" 
                  @click="doDelete(false)">
            仅删除当前任务
          </button>
          <button class="w-full py-2 bg-red-600 text-white rounded hover:bg-red-700" 
                  @click="doDelete(true)">
            删除整个计划 (及后续任务)
          </button>
          <button class="w-full py-2 text-gray-500 hover:bg-gray-100 rounded mt-2" 
                  @click="cancelDelete">
            取消
          </button>
        </div>
      </div>
    </div>

    <!-- Add Dialog -->
    <div v-if="showAdd" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50" @click.self="showAdd = false">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-4xl h-[80vh] flex flex-col">
        <div class="px-6 py-4 border-b flex justify-between items-center">
          <h2 class="text-lg font-semibold">新增复盘</h2>
          <button @click="showAdd = false" class="text-gray-500 hover:text-gray-700">&times;</button>
        </div>
        
        <div class="flex-1 flex overflow-hidden">
          <!-- Left: Knowledge Tree & List -->
          <div class="w-1/3 border-r flex flex-col">
            <div class="h-1/2 border-b overflow-auto p-2">
              <KnowledgeFolderTree @select="onFolderSelect" />
            </div>
            <div class="h-1/2 flex flex-col">
              <div class="p-2 border-b">
                <input v-model="kKeyword" class="w-full border rounded px-2 py-1" placeholder="搜索知识点..." @input="loadKnowledge" />
              </div>
              <div class="flex-1 overflow-auto p-2 space-y-1">
                <div v-for="k in kList" :key="k.id" 
                     class="cursor-pointer px-2 py-1 rounded hover:bg-gray-100"
                     :class="{ 'bg-blue-50 text-blue-600': selectedK?.id === k.id }"
                     @click="selectKnowledge(k)">
                  {{ k.title }}
                </div>
                <div v-if="kList.length === 0" class="text-gray-400 text-center text-sm mt-4">无知识点</div>
              </div>
            </div>
          </div>

          <!-- Middle: Cards -->
          <div class="w-1/3 border-r flex flex-col">
            <div class="p-2 border-b font-medium bg-gray-50">问题卡片</div>
            <div class="flex-1 overflow-auto p-2">
              <div v-if="!selectedK" class="text-gray-400 text-center mt-4">请选择知识点</div>
              <div v-else class="space-y-2">
                <label class="flex items-center gap-2 p-2 hover:bg-gray-50 rounded cursor-pointer">
                  <input type="checkbox" :checked="isAllSelected" @change="toggleAll" />
                  <span class="font-medium">全选</span>
                </label>
                <div v-for="c in currentCards" :key="c.id" class="flex items-start gap-2 p-2 hover:bg-gray-50 rounded border">
                  <input type="checkbox" :value="c.id" v-model="selectedCardIds" class="mt-1" />
                  <div class="text-sm">
                    <div class="font-medium">{{ c.question }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Right: Plan Settings -->
          <div class="w-1/3 flex flex-col p-4 space-y-4 bg-gray-50">
            <div class="font-medium">复盘计划</div>
            <select v-model="planType" class="w-full border rounded px-3 py-2">
              <option value="ebbinghaus">艾宾浩斯遗忘曲线</option>
              <option value="daily">每天 (未来30天)</option>
              <option value="weekly">每周 (未来12周)</option>
              <option value="monthly">每月 (未来12月)</option>
              <option value="custom">自定义间隔</option>
            </select>

            <div v-if="planType === 'custom'" class="space-y-2">
              <label class="text-sm text-gray-600">间隔天数</label>
              <input type="number" v-model.number="customInterval" class="w-full border rounded px-3 py-2" min="1" />
            </div>

            <div class="flex-1"></div>
            <div class="text-sm text-gray-500">
              已选择 {{ selectedCardIds.length }} 个问题
            </div>
            <button class="w-full bg-blue-600 text-white py-2 rounded hover:bg-blue-700 disabled:opacity-50"
                    :disabled="!selectedCardIds.length"
                    @click="submitPlan">
              确定添加
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import api from '../api'
import KnowledgeFolderTree from '../components/KnowledgeFolderTree.vue'
import { useKnowledgeFolderStore } from '../stores/knowledgeFolders'

// Calendar State
const currentDate = ref(new Date())
const selectedDate = ref(new Date())
const tasks = ref([])

// Helper: Date formatting
const formatDate = (d) => {
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${y}-${m}-${day}`
}

const currentYear = computed(() => currentDate.value.getFullYear())
const currentMonth = computed(() => currentDate.value.getMonth() + 1)

const weekDays = computed(() => {
  const curr = new Date(currentDate.value)
  const day = curr.getDay() // 0=Sun
  const diff = curr.getDate() - day + (day === 0 ? -6 : 1) // Adjust to Mon
  const monday = new Date(curr.setDate(diff))
  
  const days = []
  for (let i = 0; i < 7; i++) {
    const d = new Date(monday)
    d.setDate(monday.getDate() + i)
    days.push({
      name: ['周日','周一','周二','周三','周四','周五','周六'][d.getDay()],
      day: d.getDate(),
      date: new Date(d)
    })
  }
  return days
})

const isToday = (d) => formatDate(d) === formatDate(new Date())
const isSelected = (d) => formatDate(d) === formatDate(selectedDate.value)

const prevWeek = () => {
  const d = new Date(currentDate.value)
  d.setDate(d.getDate() - 7)
  currentDate.value = d
}
const nextWeek = () => {
  const d = new Date(currentDate.value)
  d.setDate(d.getDate() + 7)
  currentDate.value = d
}
const goToToday = () => {
  currentDate.value = new Date()
  selectedDate.value = new Date()
}
const selectDate = (d) => { selectedDate.value = d }

// Task Loading
const loadTasks = async () => {
  const start = new Date(weekDays.value[0].date)
  start.setDate(start.getDate() - 7)
  const end = new Date(weekDays.value[6].date)
  end.setDate(end.getDate() + 7)
  
  const res = await api.get('/api/reviews', { params: { 
    start_date: start.toISOString(), 
    end_date: end.toISOString() 
  }})
  
  const allTasks = res.data
  
  // Collect unique knowledge IDs
  const kIds = [...new Set(allTasks.map(t => t.knowledge_id))]
  await fetchKnowledgeDetails(kIds)
  
  tasks.value = allTasks
}

// Knowledge Cache
const knowledgeCache = ref({})
const fetchKnowledgeDetails = async (ids) => {
  const missing = ids.filter(id => !knowledgeCache.value[id])
  if (missing.length === 0) return
  
  await Promise.all(missing.map(async id => {
    try {
      const res = await api.get(`/api/knowledge/${id}`)
      knowledgeCache.value[id] = res.data
      // Parse cards
      const cards = parseBody(res.data.body).cards
      knowledgeCache.value[id].cardsMap = {}
      cards.forEach(c => knowledgeCache.value[id].cardsMap[c.id] = c)
    } catch {}
  }))
}

// Helper to parse body (copied from Knowledge.vue)
const parseBody = (html) => {
  const res = { cards: [] }
  try {
    const div = document.createElement('div'); div.innerHTML = html || ''
    div.querySelectorAll('section.qa').forEach((sec) => {
      const h = sec.querySelector('h3')
      const question = (h?.textContent || '').trim()
      if (h) h.remove()
      const answerHtml = sec.innerHTML.trim()
      const id = sec.getAttribute('data-id') || sec.id
      if (id) res.cards.push({ id, question, answerHtml })
    })
  } catch {}
  return res
}

const getTasksForDate = (date) => {
  const s = formatDate(date)
  return tasks.value.filter(t => formatDate(new Date(t.due_date)) === s)
}

const selectedTasks = computed(() => {
  const list = getTasksForDate(selectedDate.value)
  return list.map(t => {
    const k = knowledgeCache.value[t.knowledge_id]
    const card = k?.cardsMap?.[t.card_id]
    return {
      ...t,
      knowledge_title: k?.title || 'Unknown',
      question: card?.question || 'Loading...',
      answer: card?.answerHtml || ''
    }
  })
})

const sortedTasks = computed(() => {
  return [...selectedTasks.value].sort((a, b) => {
    if (a.status === b.status) return 0
    return a.status === 'done' ? 1 : -1
  })
})

const getCardQuestion = (t) => {
  const k = knowledgeCache.value[t.knowledge_id]
  const card = k?.cardsMap?.[t.card_id]
  return card?.question || 'Loading...'
}

// Review Modal Logic
const showReview = ref(false)
const currentReviewTask = ref(null)
const showAnswer = ref(false)

const openReviewModal = (t) => {
  currentReviewTask.value = t
  showAnswer.value = false
  showReview.value = true
}
const closeReviewModal = () => {
  showReview.value = false
  currentReviewTask.value = null
}
const completeReview = async () => {
  if (!currentReviewTask.value) return
  await api.put(`/api/reviews/${currentReviewTask.value.id}/status`, null, { params: { status: 'done' } })
  closeReviewModal()
  await loadTasks()
}

const jumpToKnowledge = (t) => {
  if (!t) return
  // Use the router instance from useRoute/useRouter if available, or window.location as fallback
  // Since we are in setup, we can use useRouter
  import('vue-router').then(({ useRouter }) => {
     // This won't work inside a callback because useRouter must be called in setup
     // We need to move useRouter to top level
  })
}

// Move useRouter to top level
import { useRouter } from 'vue-router'
const router = useRouter()

const jumpToKnowledgeAction = (t) => {
  if (!t) return
  router.push({ name: 'knowledge', query: { id: t.knowledge_id, card: t.card_id } })
}

// Delete Logic
const showDelete = ref(false)
const taskToDelete = ref(null)

const confirmDelete = (t) => {
  taskToDelete.value = t
  showDelete.value = true
}
const cancelDelete = () => {
  showDelete.value = false
  taskToDelete.value = null
}
const doDelete = async (deletePlan) => {
  if (!taskToDelete.value) return
  try {
    await api.delete(`/api/reviews/${taskToDelete.value.id}`, { params: { delete_plan: deletePlan } })
    showDelete.value = false
    taskToDelete.value = null
    await loadTasks()
  } catch (e) {
    alert('删除失败')
  }
}

// Add Dialog
const showAdd = ref(false)
const kList = ref([])
const kKeyword = ref('')
const selectedK = ref(null)
const currentCards = ref([])
const selectedCardIds = ref([])
const planType = ref('ebbinghaus')
const customInterval = ref(1)
const selectedFolderId = ref(null)
const folderStore = useKnowledgeFolderStore()

const openAdd = async () => {
  showAdd.value = true
  await folderStore.load()
  loadKnowledge()
}

const onFolderSelect = (id) => {
  selectedFolderId.value = id
  loadKnowledge()
}

const loadKnowledge = async () => {
  const params = { folder_id: selectedFolderId.value || undefined }
  const res = await api.get('/api/knowledge', { params })
  const q = kKeyword.value.trim().toLowerCase()
  kList.value = q ? res.data.filter(k => k.title.toLowerCase().includes(q)) : res.data
}

const selectKnowledge = async (k) => {
  selectedK.value = k
  // Fetch full detail to get body
  const res = await api.get(`/api/knowledge/${k.id}`)
  const parsed = parseBody(res.data.body)
  currentCards.value = parsed.cards
  selectedCardIds.value = []
}

const isAllSelected = computed(() => {
  return currentCards.value.length > 0 && selectedCardIds.value.length === currentCards.value.length
})

const toggleAll = () => {
  if (isAllSelected.value) {
    selectedCardIds.value = []
  } else {
    selectedCardIds.value = currentCards.value.map(c => c.id)
  }
}

const submitPlan = async () => {
  if (!selectedK.value || !selectedCardIds.value.length) return
  
  const payload = {
    knowledge_id: selectedK.value.id,
    card_ids: selectedCardIds.value,
    plan_type: planType.value,
    custom_interval: planType.value === 'custom' ? customInterval.value : undefined
  }
  
  try {
    await api.post('/api/reviews/plan', payload)
    showAdd.value = false
    await loadTasks()
    alert('添加成功')
  } catch (e) {
    alert('添加失败')
  }
}

watch([currentDate], () => {
  loadTasks()
}, { immediate: true })

</script>

<style>
@import "https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css";

/* Custom Prose Styles for Rich Text */
.prose {
  color: #374151;
  line-height: 1.6;
}
.prose h1, .prose h2, .prose h3 {
  color: #111827;
  font-weight: 600;
  margin-top: 1.5em;
  margin-bottom: 0.5em;
}
.prose p {
  margin-top: 1em;
  margin-bottom: 1em;
}
.prose ul {
  list-style-type: disc;
  padding-left: 1.5em;
  margin-top: 1em;
  margin-bottom: 1em;
}
.prose ol {
  list-style-type: decimal;
  padding-left: 1.5em;
  margin-top: 1em;
  margin-bottom: 1em;
}
.prose blockquote {
  border-left: 4px solid #e5e7eb;
  padding-left: 1em;
  color: #4b5563;
  font-style: italic;
  margin: 1em 0;
}
.prose table {
  width: 100%;
  border-collapse: collapse;
  margin: 1em 0;
}
.prose th, .prose td {
  border: 1px solid #d1d5db;
  padding: 0.5em;
  text-align: left;
}
.prose th {
  background-color: #f3f4f6;
  font-weight: 600;
}
.prose code {
  background-color: #f3f4f6;
  padding: 0.2em 0.4em;
  border-radius: 0.25em;
  font-family: monospace;
  font-size: 0.9em;
}
.prose pre {
  background-color: #1f2937;
  color: #f3f4f6;
  padding: 1em;
  border-radius: 0.5em;
  overflow-x: auto;
}
.prose img {
  max-width: 100%;
  height: auto;
  border-radius: 0.5em;
}
</style>
